<?php

namespace app\index\controller;

use app\common\service\OperationToken;
use app\index\model\Addresses;
use app\index\model\Admins;
use app\index\model\Users;
use Firebase\JWT\JWT;
use think\Controller;

class UserCtl extends Controller
{
    /*
     * 用户登录
     */
    public function login()
    {
        // 首先找出手机号匹配的记录
        $user = Users::where('phone', input('phone'))->with('addresses')->find();
        if ($user != null) {
            // 不为空则验证密码
            if (password_verify(input('password'), $user->password)) {
                // 密码匹配则生成 token
                $user->token = OperationToken::createToken($user->id, 0);
                return json($user->hidden(['password']));
            }
        }
        return json(['msg' => '手机号或密码错误'], 401);
    }

    /*
     * 管理员登录
     */
    public function adminLogin()
    {
        // 首先找出手机号匹配的记录
        $admin = Admins::where('username', input('username'))->find();
        if ($admin != null) {
            // 不为空则验证密码
            if (password_verify(input('password'), $admin['password'])) {
                // 密码匹配则生成 token
                $admin->token = OperationToken::createToken($admin->id, 1);
                $res['data'] = $admin->hidden(['password']);
                $res['code'] = 20000;
                return json($res);
            }
        }
        return json(['msg' => '用户名或密码错误', 'code' => 40003]);
    }

    /*
     * 获取管理员的信息
     */
    public function getAdminInfo()
    {
        $token = input('token');
        $de_token = JWT::decode($token, getJwtKey(), ['HS256']);
        $admin = Admins::where('id', $de_token->data->uid)->find();
        $res['data'] = $admin;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 注册
     */
    public function register()
    {
        $phone = input('phone');
        // 由于手机号必须是唯一的，所以先去查询是否已存在
        if (Users::where('phone', $phone)->find() == null) {
            $user = new Users;
            $user->save([
                'phone' => $phone,
                'password' => password_hash(input('password'), PASSWORD_BCRYPT),
                'username' => $phone,
                'email' => null,
                'avatar' => '',
                'createdAt' => time()
            ]);
            $user->token = OperationToken::createToken($user->id, 0);    // 注册成功，生成 token
            return json($user->hidden(['password']));
        } else {
            return json(['msg' => '该手机号已被占用'])->code(401);
        }
    }

    /*
     * 修改密码前验证旧密码
     */
    public function checkOldPass()
    {
        $oldPass = Users::where('id', input('uid'))->value('password');
        // 比较输入的密码与用户密码
        if (password_verify(input('password'), $oldPass)) {
            return json(['msg' => '验证通过', 'code' => 200]);
        }
        return json(['msg' => '验证失败', 'code' => 401]);
    }

    /*
     * 修改密码
     */
    public function updPassword()
    {
        Users::update([
            'id' => input('uid'),
            'password' => password_hash(input('password'), PASSWORD_BCRYPT)
        ]);
        return json(['msg' => '修改成功']);
    }

    /*
     * 通过 uid 获取用户基本信息
     */
    public function getInfoById()
    {
        return json(['data' => Users::get(input('uid'))->hidden(['password'])]);
    }

    /*
     * 更新用户信息
     */
    public function updUserInfo()
    {
        // 检验手机号
        if (input('?post.phone')) {
            if (Users::where('phone', input('phone'))->where('id', '<>', input('id'))->find() != null) {
                return json(['msg' => "该手机号已被占用"], 403);
            }
        }
        // 检验邮箱
        if (input('?post.email')) {
            if (Users::where('email', input('email'))->where('id', '<>', input('id'))->find() != null) {
                return json(['msg' => "该邮箱已被占用"], 403);
            }
        }
        // 若有头像上传操作，则做相应处理
        if (input('?file.avatar')) {
            $avatar = uploadAvatar("avatar");
        } else {
            $avatar = input('avatar');
        }
        return json(Users::update([
            'id' => input('id'),
            'username' => input('username'),
            'email' => input('email'),
            'phone' => input('phone'),
            'avatar' => $avatar,
            'sex' => input('sex'),
            'city' => input('city'),
            'address' => input('address')
        ])->hidden(['password']));
    }

    /*
     * 添加收货地址
     */
    public function addAddress()
    {
        $isDefault = Addresses::where('uid', input('uid'))->count() > 0 ? 0 : 1;
        Addresses::create([
            'addr' => input('addr'),
            'receiver' => input('receiver'),
            'phone' => input('phone'),
            'uid' => input('uid'),
            'isdefault' => $isDefault
        ]);
        return json(['msg' => '添加成功！']);
    }

    /*
     * 删除收货地址
     */
    public function delAddress()
    {
        Addresses::destroy(input('id'));
        return json(['msg' => '删除成功！']);
    }

    /*
     * 获取某用户的所有收货地址
     */
    public function getAddressesByUid()
    {
        return json(Addresses::where('uid', input('uid'))->select());
    }

    /*
     * 设置默认地址
     */
    public function setDefaultAddress()
    {
        $defaultAddr = Addresses::where(['uid' => input('uid'), 'isdefault' => 1])->find();
        if ($defaultAddr != null && input('id') != $defaultAddr->id) {
            $defaultAddr->isdefault = 0;
            $defaultAddr->save();
        }
        Addresses::update([
            'id' => input('id'),
            'isdefault' => 1
        ]);
        return json(['msg' => '设置成功！']);
    }

    /*
     * 更新某条收货地址
     */
    public function updAddress()
    {
        Addresses::update([
            'id' => input('id'),
            'addr' => input('addr'),
            'receiver' => input('receiver'),
            'phone' => input('phone')
        ]);
        return json(['msg' => '更新成功！']);
    }
}